package com.example.myfoodrecipe.viewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.myfoodrecipe.data.local.LocalRepository
import com.example.myfoodrecipe.data.local.entity.FavoriteEntity
import com.example.myfoodrecipe.data.model.Result
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class FavViewModel(application: Application): AndroidViewModel(application) {
    private val localRepository = LocalRepository(application)
    val favorites: MutableLiveData<List<FavoriteEntity>> = MutableLiveData()

    //点击favFragment获取所有收藏
    fun getAllFav() {
        viewModelScope.launch {
            localRepository.getAllFav().collect {
                favorites.value = it
            }
        }
    }

    //插入收藏食谱
    fun insertFav(result: Result){
        viewModelScope.launch {
            val favoriteEntity = FavoriteEntity(0,result)
            localRepository.insertFav(favoriteEntity)
            }
        }



    //删除收藏食谱
    fun deleteFav(favoriteEntity: FavoriteEntity){
        viewModelScope.launch {
            localRepository.deleteFav(favoriteEntity)
        }
    }



}